﻿@page "/product"
@using System.Text.Json
@using BlazorCRUD.App.Components.BaseComponents
@using BlazorCRUD.App.Models
@inject IHttpClientFactory httpClientFactory
@inject IToastService toastService

<h3>Products</h3>

@if (productModels == null)
{
    <p>Loading...</p>
}
else
{
    <a class="btn btn-primary" href="/product/create">Create</a>
    <table class="table">
        <thead>
            <tr>
                <th>Name</th>
                <th>Description</th>
                <th>Quantity</th>
                <th>Price</th>
                <th>CreatedAt</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var product in productModels)
            {
                <tr>
                    <td>@product.Name</td>
                    <td>@product.Description</td>
                    <td>@product.Quantity</td>
                    <td>@product.Price</td>
                    <td>@product.CreatedDate.ToShortDateString()</td>
                    <td>
                        <a class="btn btn-primary" href="/product/update/@product.Id">Update</a>
                        <button class="btn btn-danger" @onclick="()=> { deleteId=product.Id; appModal.Open(); }">Delete</button>
                    </td>
                </tr>
            }
        </tbody>
    </table>

    <AppModal @ref="appModal">
        <Title>Notification</Title>
        <Body>
            Do you sure want to delete this product?
        </Body>
        <Footer>
            <button type="button" class="btn btn-primary" style="width:80px" @onclick="DeleteAsync">Yes</button>
            <button type="button" class="btn btn-secondary" data-dismiss="modal" @onclick="()=>appModal.Close()">Cancel</button>
        </Footer>
    </AppModal>
}

@code {
    private List<ProductModel>? productModels = null;
    private AppModal appModal { get; set; }
    private Guid deleteId { get; set; }

    protected override async Task OnInitializedAsync()
    {
        await LoadProducts();
    }

    protected async Task LoadProducts()
    {
        var httpClient = httpClientFactory.CreateClient();

        var httpResponse = await httpClient.GetAsync("https://localhost:7277/Product");
        var responseContent = await httpResponse.Content.ReadAsStringAsync();
        productModels = JsonSerializer.Deserialize<List<ProductModel>>(responseContent, new JsonSerializerOptions()
            {
                PropertyNameCaseInsensitive = true
            });
    }

    public async Task DeleteAsync()
    {
        var httpClient = httpClientFactory.CreateClient();

        var httpResponse = await httpClient.DeleteAsync($"https://localhost:7277/Product/{deleteId}");
        if (httpResponse.IsSuccessStatusCode)
        {
            toastService.ShowSuccess("Delete product successfully");
            await LoadProducts();
            appModal.Close();
        }
    }
}
